<template>
  <div class="container">
    <van-cell-group class="group">
      <van-field :value="userName" required clearable label="昵称" placeholder="请输入昵称" @change="inputName"/>
      <van-field :value="wxCode" clearable label="微信号" placeholder="请输入微信号" @change="inputCode"/>
      <view class="section">
        <picker mode="date" :value="birthday" @change="bindDateChange">
          <view class="picker">
            <van-field :value="birthday" readonly  clearable label="生日" placeholder="请输入生日" />
          </view>
        </picker>
      </view>
      <view class="section">
      <picker :value="sex" :range="selectSex" @change="bindSex">
        <view class="picker">
          <van-field :value="sex" readonly clearable label="性别" placeholder="请选择性别"/>
        </view>
      </picker>
    </view>
    </van-cell-group>
    <div class="btn">
      <van-button class="mk-button" block type="primary" @click="saveUser">保存</van-button>
    </div>

    <van-toast id="van-toast" />
  </div>
</template>
<script>
import {mapState} from 'vuex'
import Toast from 'vant-weapp/dist/toast/toast'
import * as UserAction from '@/api/user'

export default {
  data () {
    return {
      selectSex: ['男', '女'],
      sexId: null,
      selectSexStatus: false,
      userName: '',
      wxCode: '',
      sex: '',
      birthday: ''
    }
  },
  computed: {
    ...mapState(['me'])
  },
  methods: {
    saveUser () {
      let params = {
        nickname: this.userName,
        wechat_no: this.wxCode,
        sex: this.sexId * 1,
        birthday: this.birthday
      }
      if (!this.userName) {
        Toast('昵称不得为空')
        return
      }
      UserAction.storeProfile(params).then((data) => {
        this.$store.commit('set_me', data)
        Toast('保存成功')
        setTimeout(() => {
          wx.switchTab({ url: './index' })
        }, 1000)
      }).catch(err => Toast(err.msg))
    },
    bindDateChange (e) {
      this.birthday = e.target.value
    },
    inputCode (event) {
      this.wxCode = event.mp.detail
    },
    inputName (event) {
      this.userName = event.mp.detail
    },
    showSex (e) {
      this.selectSexStatus = !this.selectSexStatus
    },
    bindSex (e) {
      this.sex = this.selectSex[e.target.value]
      this.sexId = e.target.value
      this.showSex()
    }
  },
  beforeMount () {
    this.userName = this.me.nickname
    this.wxCode = this.me.wechat_no
    this.birthday = this.me.birthday
    this.sex = this.selectSex[this.me.sex]
  }
}
</script>

<style lang="less" scoped>
  .group{
    margin: 10rpx;
  }
  .btn{
    margin: 10rpx;
  }
</style>

